<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>抖音个人主页监控器</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
            display: flex;
            min-height: 80vh;
        }

        .sidebar {
            width: 250px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 0;
            flex-shrink: 0;
        }

        .sidebar-header {
            padding: 30px 20px;
            text-align: center;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

        .sidebar-header h1 {
            font-size: 1.5em;
            margin-bottom: 5px;
        }

        .sidebar-header p {
            opacity: 0.9;
            font-size: 0.9em;
        }

        .nav-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .nav-item {
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

        .nav-link {
            display: block;
            padding: 20px;
            color: white;
            text-decoration: none;
            transition: background-color 0.3s;
            cursor: pointer;
        }

        .nav-link:hover {
            background-color: rgba(255,255,255,0.1);
        }

        .nav-link.active {
            background-color: rgba(255,255,255,0.2);
            border-right: 4px solid white;
        }

        .nav-icon {
            margin-right: 10px;
            font-size: 1.2em;
        }

        .main-content {
            flex: 1;
            padding: 30px;
            overflow-y: auto;
        }

        .module {
            display: none;
        }

        .module.active {
            display: block;
        }

        .section {
            margin-bottom: 30px;
            padding: 25px;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            background: #fafafa;
        }

        .section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.5em;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #555;
        }

        .form-group input, .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        .form-group input:focus, .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
        }

        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: transform 0.2s, box-shadow 0.2s;
            margin-right: 10px;
            margin-bottom: 10px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .btn-danger {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
        }

        .btn-danger:hover {
            box-shadow: 0 5px 15px rgba(255, 107, 107, 0.4);
        }

        .btn-success {
            background: linear-gradient(135deg, #51cf66 0%, #40c057 100%);
        }

        .btn-success:hover {
            box-shadow: 0 5px 15px rgba(81, 207, 102, 0.4);
        }

        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-monitoring {
            background: #51cf66;
            animation: pulse 2s infinite;
        }

        .status-stopped {
            background: #ff6b6b;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        .homepage-list {
            background: white;
            border-radius: 8px;
            overflow: hidden;
        }

        .homepage-item {
            padding: 15px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: background-color 0.2s;
        }

        .homepage-item:hover {
            background-color: #f8f9fa;
        }

        .homepage-item:last-child {
            border-bottom: none;
        }

        .homepage-info {
            flex: 1;
        }

        .homepage-url {
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }

        .homepage-nickname {
            color: #007bff;
            font-size: 14px;
            margin-bottom: 5px;
            font-weight: 500;
        }

        .homepage-status {
            font-size: 12px;
            color: #666;
        }

        .homepage-actions {
            display: flex;
            gap: 10px;
        }

        .logs {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            height: 500px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 14px;
        }
        
        .log-entry {
            margin-bottom: 5px;
            padding: 8px;
            border-radius: 4px;
            border-left: 4px solid #dee2e6;
            transition: all 0.2s ease;
        }
        
        .log-entry:hover {
            background: #e9ecef;
        }
        
        .log-entry.INFO {
            border-left-color: #17a2b8;
            background: rgba(23, 162, 184, 0.05);
        }
        
        .log-entry.SUCCESS {
            border-left-color: #28a745;
            background: rgba(40, 167, 69, 0.05);
        }
        
        .log-entry.WARNING {
            border-left-color: #ffc107;
            background: rgba(255, 193, 7, 0.05);
        }
        
        .log-entry.ERROR {
            border-left-color: #dc3545;
            background: rgba(220, 53, 69, 0.05);
        }
        
        .log-entry.COOKIE {
            border-left-color: #fd7e14;
            background: rgba(253, 126, 20, 0.05);
        }
        
        .log-entry.MONITOR {
            border-left-color: #6f42c1;
            background: rgba(111, 66, 193, 0.05);
        }
        
        .log-entry.DOWNLOAD {
            border-left-color: #20c997;
            background: rgba(32, 201, 151, 0.05);
        }
        
        .log-timestamp {
            color: #6c757d;
            font-size: 12px;
            margin-right: 8px;
        }
        
        .log-message {
            color: #495057;
        }

        .add-homepage {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        .add-homepage input {
            flex: 1;
        }

        .config-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        @media (max-width: 768px) {
            .config-grid {
                grid-template-columns: 1fr;
            }
            
            .homepage-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            
            .homepage-actions {
                width: 100%;
                justify-content: flex-end;
            }
        }

        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #51cf66;
            color: white;
            padding: 15px 20px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
            transform: translateX(400px);
            transition: transform 0.3s;
            z-index: 1000;
        }

        .notification.show {
            transform: translateX(0);
        }

        .notification.error {
            background: #ff6b6b;
        }

        .cookie-history-item {
            padding: 12px;
            border: 1px solid #eee;
            border-radius: 6px;
            margin-bottom: 10px;
            background: #f9f9f9;
        }

        .cookie-history-item:last-child {
            margin-bottom: 0;
        }

        .cookie-timestamp {
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }

        .cookie-status {
            color: #51cf66;
            font-size: 12px;
            margin-bottom: 8px;
        }

        .cookie-value {
            font-family: 'Courier New', monospace;
            font-size: 11px;
            color: #666;
            background: white;
            padding: 8px;
            border-radius: 4px;
            border: 1px solid #ddd;
            word-break: break-all;
            max-height: 60px;
            overflow-y: auto;
        }

        .cookie-actions {
            margin-top: 8px;
            text-align: right;
        }

        .btn-small {
            padding: 4px 8px;
            font-size: 11px;
            margin-left: 5px;
        }

        /* 视频列表样式 */
        .video-item {
            padding: 15px;
            border-bottom: 1px solid #eee;
            display: flex;
            align-items: center;
            transition: background-color 0.2s;
        }

        .video-item:hover {
            background-color: #f8f9fa;
        }

        .video-item:last-child {
            border-bottom: none;
        }

        .video-info {
            flex: 1;
            margin-right: 15px;
        }

        .video-title {
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
            font-size: 14px;
            line-height: 1.4;
        }

        .video-meta {
            display: flex;
            gap: 15px;
            font-size: 12px;
            color: #666;
            margin-bottom: 5px;
        }

        .video-status {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 500;
        }

        .status-waiting {
            background: #e3f2fd;
            color: #1976d2;
        }

        .status-downloading {
            background: #fff3e0;
            color: #f57c00;
        }

        .status-completed {
            background: #e8f5e8;
            color: #2e7d32;
        }

        .status-failed {
            background: #ffebee;
            color: #c62828;
        }

        .video-actions {
            display: flex;
            gap: 8px;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
        }

        .pagination button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .pagination button:hover:not(:disabled) {
            background: #f8f9fa;
            border-color: #667eea;
        }

        .pagination button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .pagination .current-page {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .video-link {
            color: #007bff;
            text-decoration: none;
            font-size: 11px;
        }

        .video-link:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 侧边栏导航 -->
        <div class="sidebar">
            <div class="sidebar-header">
                <h1>🎵 抖音监控器</h1>
                <p>智能监控管理系统</p>
            </div>
            <ul class="nav-menu">
                <li class="nav-item">
                    <a class="nav-link active" onclick="showModule('dashboard')">
                        <span class="nav-icon">📊</span>监控面板
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" onclick="showModule('config')">
                        <span class="nav-icon">⚙️</span>系统配置
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" onclick="showModule('homepage')">
                        <span class="nav-icon">👤</span>主页管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" onclick="showModule('videos')">
                        <span class="nav-icon">📹</span>视频列表
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" onclick="showModule('logs')">
                        <span class="nav-icon">📝</span>运行日志
                    </a>
                </li>
            </ul>
        </div>

        <!-- 主内容区域 -->
        <div class="main-content">
            <!-- 监控面板模块 -->
            <div id="dashboard" class="module active">
                <h2>监控面板</h2>
                <div class="section">
                    <h3>监控状态</h3>
                    <div style="display: flex; align-items: center; margin-bottom: 20px;">
                        <span class="status-indicator" id="statusIndicator"></span>
                        <span id="statusText">未知状态</span>
                    </div>
                    <button class="btn btn-success" id="startBtn" onclick="startMonitoring()">开始监控</button>
                    <button class="btn btn-danger" id="stopBtn" onclick="stopMonitoring()" disabled>停止监控</button>
                </div>
                
                <!-- 快速统计 -->
                <div class="section">
                    <h3>监控统计</h3>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px;">
                        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; text-align: center;">
                            <div style="font-size: 2em; color: #667eea; margin-bottom: 10px;" id="homepageCount">0</div>
                            <div style="color: #666;">监控主页数</div>
                        </div>
                        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; text-align: center;">
                            <div style="font-size: 2em; color: #51cf66; margin-bottom: 10px;" id="videoCount">0</div>
                            <div style="color: #666;">发现视频数</div>
                        </div>
                        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; text-align: center;">
                            <div style="font-size: 2em; color: #ffc107; margin-bottom: 10px;" id="downloadingCount">0</div>
                            <div style="color: #666;">下载中</div>
                        </div>
                        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; text-align: center;">
                            <div style="font-size: 2em; color: #28a745; margin-bottom: 10px;" id="completedCount">0</div>
                            <div style="color: #666;">已完成</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 系统配置模块 -->
            <div id="config" class="module">
                <h2>系统配置</h2>
                <div class="section">
                    <h3>基础配置</h3>
                    <div class="config-grid">
                        <div class="form-group">
                            <label for="cookie">Cookie:</label>
                            <textarea id="cookie" rows="3" placeholder="请输入抖音Cookie"></textarea>
                            <div style="margin-top: 10px;">
                                <button class="btn btn-success" onclick="autoGetCookies()">🔄 自动获取Cookie</button>
                                <button class="btn" onclick="toggleCookieHistory()">📋 查看历史记录</button>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="checkInterval">检查间隔 (秒):</label>
                            <input type="number" id="checkInterval" value="300" min="60">
                        </div>
                        <div class="form-group">
                            <label for="downloadPath">下载路径:</label>
                            <input type="text" id="downloadPath" value="./下载">
                        </div>
                        <div class="form-group">
                            <label for="videoTimeFilter">监控发布时间 (分钟):</label>
                            <input type="number" id="videoTimeFilter" value="60" min="1" placeholder="只监控指定分钟内发布的视频">
                            <small style="color: #666; font-size: 12px;">只监控指定分钟内发布的视频</small>
                        </div>
                    </div>
                </div>
                
                <!-- 语音提醒配置 -->
                <div class="section">
                    <h3>🔊 语音提醒设置</h3>
                    <div class="config-grid">
                        <div class="form-group">
                            <label>
                                <input type="checkbox" id="enableSoundNotification" style="margin-right: 8px;">
                                启用语音提醒
                            </label>
                            <small style="color: #666; font-size: 12px; display: block; margin-top: 5px;">发现新视频时播放提示音</small>
                        </div>
                        <div class="form-group">
                            <label for="soundFilePath">自定义提示音文件:</label>
                            <input type="text" id="soundFilePath" placeholder="留空使用系统默认提示音">
                            <small style="color: #666; font-size: 12px;">支持 .wav 格式音频文件</small>
                        </div>
                    </div>
                    <div style="margin-top: 15px;">
                        <button class="btn" onclick="testSound()">🎵 测试提示音</button>
                        <button class="btn" onclick="testSound(3)">🎵 测试多个视频提示音</button>
                        <button class="btn" onclick="saveSoundConfig()">保存语音设置</button>
                    </div>
                </div>
                
                <div style="margin-top: 20px;">
                    <button class="btn" onclick="saveConfig()">保存配置</button>
                </div>
                
                <!-- Cookie历史记录 -->
                <div id="cookieHistorySection" style="display: none; margin-top: 20px; padding: 20px; background: white; border-radius: 8px; border: 1px solid #ddd;">
                    <h3 style="margin-bottom: 15px; color: #333;">Cookie历史记录</h3>
                    <div id="cookieHistoryList" style="max-height: 300px; overflow-y: auto;">
                        <!-- Cookie历史记录将在这里显示 -->
                    </div>
                </div>
            </div>

            <!-- 主页管理模块 -->
            <div id="homepage" class="module">
                <h2>个人主页管理</h2>
                <div class="section">
                    <h3>添加新主页</h3>
                    <div class="add-homepage">
                        <input type="text" id="homepageUrl" placeholder="请输入抖音个人主页URL或用户ID">
                        <button class="btn" onclick="addHomepage()">添加主页</button>
                    </div>
                </div>
                <div class="section">
                    <h3>监控列表</h3>
                    <div class="homepage-list" id="homepageList">
                        <!-- 主页列表将在这里动态生成 -->
                    </div>
                </div>
            </div>

            <!-- 视频列表模块 -->
            <div id="videos" class="module">
                <h2>📹 发现的视频列表</h2>
                
                <!-- 过滤和操作区域 -->
                <div class="section">
                    <h3>筛选与操作</h3>
                    <div style="display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; align-items: center;">
                        <input type="text" id="authorFilter" placeholder="按作者筛选" style="flex: 1; min-width: 150px;">
                        <select id="statusFilter" style="padding: 12px; border: 2px solid #ddd; border-radius: 8px;">
                            <option value="">全部状态</option>
                            <option value="待下载">待下载</option>
                            <option value="下载中">下载中</option>
                            <option value="已下载">已下载</option>
                            <option value="下载失败">下载失败</option>
                        </select>
                        <button class="btn" onclick="loadVideoList()">🔍 筛选</button>
                        <button class="btn btn-danger" onclick="clearVideoList()">🗑️ 清空列表</button>
                    </div>
                </div>
                
                <!-- 视频列表 -->
                <div class="section">
                    <h3>视频列表</h3>
                    <div id="videoListContainer">
                        <div id="videoList" style="background: white; border-radius: 8px; overflow: hidden;">
                            <!-- 视频列表将在这里显示 -->
                        </div>
                        
                        <!-- 分页控件 -->
                        <div id="videoPagination" style="margin-top: 20px; text-align: center;">
                            <!-- 分页按钮将在这里显示 -->
                        </div>
                    </div>
                </div>
            </div>

            <!-- 运行日志模块 -->
            <div id="logs" class="module">
                <h2>运行日志</h2>
                <div class="section">
                    <div class="logs" id="logsContainer">
                        <!-- 日志将在这里显示 -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 通知 -->
    <div class="notification" id="notification"></div>

    <script>
        let currentStatus = {};
        let currentModule = 'dashboard';

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadConfig();
            updateStatus();
            loadVideoList();
            
            // 定时更新状态
            setInterval(updateStatus, 3000);
            
            // 定时更新视频列表
            setInterval(loadVideoList, 10000);
            
            // 初始化模块显示
            showModule('dashboard');
        });

        // 模块切换功能
        function showModule(moduleId) {
            // 隐藏所有模块
            const modules = document.querySelectorAll('.module');
            modules.forEach(module => {
                module.classList.remove('active');
            });
            
            // 显示指定模块
            const targetModule = document.getElementById(moduleId);
            if (targetModule) {
                targetModule.classList.add('active');
            }
            
            // 更新导航菜单状态
            const navLinks = document.querySelectorAll('.nav-link');
            navLinks.forEach(link => {
                link.classList.remove('active');
            });
            
            // 设置当前菜单项为活跃状态
            const activeLink = document.querySelector(`[onclick="showModule('${moduleId}')"]`);
            if (activeLink) {
                activeLink.classList.add('active');
            }
            
            currentModule = moduleId;
            
            // 根据模块加载相应数据
            if (moduleId === 'videos') {
                loadVideoList();
            } else if (moduleId === 'dashboard') {
                updateDashboardStats();
            } else if (moduleId === 'homepage') {
                updateHomepageList();
            }
        }

        // 更新仪表板统计数据
        function updateDashboardStats() {
            const homepages = currentStatus.config?.homepage_list || [];
            const videos = currentStatus.video_list || [];
            
            document.getElementById('homepageCount').textContent = homepages.length;
            document.getElementById('videoCount').textContent = videos.length;
            
            // 统计不同状态的视频数量
            let downloadingCount = 0;
            let completedCount = 0;
            
            videos.forEach(video => {
                if (video.download_status === '下载中') {
                    downloadingCount++;
                } else if (video.download_status === '已下载') {
                    completedCount++;
                }
            });
            
            document.getElementById('downloadingCount').textContent = downloadingCount;
            document.getElementById('completedCount').textContent = completedCount;
        }

        // 显示通知
        function showNotification(message, isError = false) {
            const notification = document.getElementById('notification');
            notification.textContent = message;
            notification.className = 'notification show' + (isError ? ' error' : '');
            
            setTimeout(() => {
                notification.classList.remove('show');
            }, 3000);
        }

        // 加载配置
        async function loadConfig() {
            try {
                const response = await fetch('/api/config');
                const config = await response.json();
                
                document.getElementById('cookie').value = config.cookie || '';
                document.getElementById('checkInterval').value = config.check_interval || 300;
                document.getElementById('downloadPath').value = config.download_path || './下载';
                document.getElementById('videoTimeFilter').value = config.video_time_filter || 60;
                
                // 加载语音配置
                await loadSoundConfig();
            } catch (error) {
                console.error('加载配置失败:', error);
            }
        }

        // 保存配置
        async function saveConfig() {
            try {
                const config = {
                    cookie: document.getElementById('cookie').value,
                    check_interval: parseInt(document.getElementById('checkInterval').value),
                    download_path: document.getElementById('downloadPath').value,
                    video_time_filter: parseInt(document.getElementById('videoTimeFilter').value)
                };
                
                const response = await fetch('/api/config', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(config)
                });
                
                const result = await response.json();
                if (result.success) {
                    showNotification('配置保存成功');
                } else {
                    showNotification('配置保存失败', true);
                }
            } catch (error) {
                showNotification('配置保存失败: ' + error.message, true);
            }
        }

        // 更新状态
        async function updateStatus() {
            try {
                const response = await fetch('/api/status');
                currentStatus = await response.json();
                
                // 更新监控状态
                const statusIndicator = document.getElementById('statusIndicator');
                const statusText = document.getElementById('statusText');
                const startBtn = document.getElementById('startBtn');
                const stopBtn = document.getElementById('stopBtn');
                
                if (currentStatus.is_monitoring) {
                    statusIndicator.className = 'status-indicator status-monitoring';
                    statusText.textContent = '监控中...';
                    startBtn.disabled = true;
                    stopBtn.disabled = false;
                } else {
                    statusIndicator.className = 'status-indicator status-stopped';
                    statusText.textContent = '已停止';
                    startBtn.disabled = false;
                    stopBtn.disabled = true;
                }
                
                // 更新主页列表
                updateHomepageList();
                
                // 更新日志
                updateLogs();
                
                // 如果Cookie历史记录区域是显示状态，则更新它
                const cookieHistorySection = document.getElementById('cookieHistorySection');
                if (cookieHistorySection.style.display === 'block') {
                    updateCookieHistoryDisplay(currentStatus.cookie_history || []);
                }
                
                // 如果当前在仪表板模块，更新统计数据
                if (currentModule === 'dashboard') {
                    updateDashboardStats();
                }
                
            } catch (error) {
                console.error('更新状态失败:', error);
            }
        }

        // 更新主页列表
        function updateHomepageList() {
            const homepageList = document.getElementById('homepageList');
            const homepages = currentStatus.config?.homepage_list || [];
            const homepageStatus = currentStatus.homepage_status || {};
            
            if (homepages.length === 0) {
                homepageList.innerHTML = '<div style="padding: 20px; text-align: center; color: #666;">暂无监控的主页</div>';
                return;
            }
            
            homepageList.innerHTML = homepages.map(homepage => {
                // 处理新格式（对象）和旧格式（字符串）
                const homepageUrl = typeof homepage === 'object' ? homepage.url : homepage;
                const nickname = typeof homepage === 'object' ? homepage.nickname : null;
                const status = homepageStatus[homepageUrl] || {};
                const lastCheck = status.last_check ? new Date(status.last_check).toLocaleString() : '从未';
                
                return `
                    <div class="homepage-item">
                        <div class="homepage-info">
                            ${nickname ? `<div class="homepage-nickname">用户: ${nickname}</div>` : ''}
                            <div class="homepage-status">
                                状态: ${status.status || '未知'} | 
                                最后检查: ${lastCheck} | 
                                新视频: ${status.new_videos_count || 0} 个
                            </div>
                        </div>
                        <div class="homepage-actions">
                            <button class="btn btn-danger" onclick="removeHomepage('${homepageUrl}')">删除</button>
                        </div>
                    </div>
                `;
            }).join('');
        }

        // 更新日志
        function updateLogs() {
            const logs = document.getElementById('logsContainer');
            const recentLogs = currentStatus.recent_logs || [];
            
            logs.innerHTML = recentLogs.map(log => {
                const level = log.level || 'INFO';
                return `
                    <div class="log-entry ${level}">
                        <span class="log-timestamp">[${log.timestamp}]</span>
                        <span class="log-message">${log.message}</span>
                    </div>
                `;
            }).join('');
            
            // 滚动到底部
            logs.scrollTop = logs.scrollHeight;
        }

        // 开始监控
        async function startMonitoring() {
            try {
                const response = await fetch('/api/monitor', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ action: 'start' })
                });
                
                const result = await response.json();
                if (result.success) {
                    showNotification('监控已开始');
                } else {
                    showNotification('启动监控失败', true);
                }
            } catch (error) {
                showNotification('启动监控失败: ' + error.message, true);
            }
        }

        // 停止监控
        async function stopMonitoring() {
            try {
                const response = await fetch('/api/monitor', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ action: 'stop' })
                });
                
                const result = await response.json();
                if (result.success) {
                    showNotification('监控已停止');
                } else {
                    showNotification('停止监控失败', true);
                }
            } catch (error) {
                showNotification('停止监控失败: ' + error.message, true);
            }
        }

        // 添加主页
        async function addHomepage() {
            const homepageUrl = document.getElementById('homepageUrl').value.trim();
            if (!homepageUrl) {
                showNotification('请输入主页URL', true);
                return;
            }
            
            try {
                const response = await fetch('/api/homepage', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ url: homepageUrl })
                });
                
                const result = await response.json();
                if (result.success) {
                    document.getElementById('homepageUrl').value = '';
                    showNotification('主页添加成功');
                    updateStatus();
                } else {
                    showNotification('主页添加失败: ' + (result.error || '未知错误'), true);
                }
            } catch (error) {
                showNotification('主页添加失败: ' + error.message, true);
            }
        }

        // 删除主页
        async function removeHomepage(homepageUrl) {
            if (!confirm('确定要删除这个主页吗？')) {
                return;
            }
            
            try {
                const response = await fetch('/api/homepage', {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ url: homepageUrl })
                });
                
                const result = await response.json();
                if (result.success) {
                    showNotification('主页删除成功');
                    updateStatus();
                } else {
                    showNotification('主页删除失败: ' + (result.error || '未知错误'), true);
                }
            } catch (error) {
                showNotification('主页删除失败: ' + error.message, true);
            }
        }

        // 自动获取Cookie
        async function autoGetCookies() {
            try {
                showNotification('正在启动Cookie获取程序，请稍候...');
                
                const response = await fetch('/api/cookies/auto', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const result = await response.json();
                if (result.success) {
                    showNotification('Cookie获取程序已启动，请查看日志获取进度');
                } else {
                    showNotification('启动Cookie获取失败: ' + (result.error || '未知错误'), true);
                }
            } catch (error) {
                showNotification('启动Cookie获取失败: ' + error.message, true);
            }
        }

        // 切换Cookie历史记录显示
        function toggleCookieHistory() {
            const section = document.getElementById('cookieHistorySection');
            if (section.style.display === 'none') {
                section.style.display = 'block';
                loadCookieHistory();
            } else {
                section.style.display = 'none';
            }
        }

        // 加载Cookie历史记录
        async function loadCookieHistory() {
            try {
                const response = await fetch('/api/cookies/history');
                const result = await response.json();
                
                if (result.success) {
                    updateCookieHistoryDisplay(result.cookie_history || []);
                } else {
                    showNotification('加载Cookie历史记录失败', true);
                }
            } catch (error) {
                showNotification('加载Cookie历史记录失败: ' + error.message, true);
            }
        }

        // 更新Cookie历史记录显示
        function updateCookieHistoryDisplay(cookieHistory) {
            const historyList = document.getElementById('cookieHistoryList');
            
            if (cookieHistory.length === 0) {
                historyList.innerHTML = '<div style="text-align: center; color: #666; padding: 20px;">暂无Cookie历史记录</div>';
                return;
            }
            
            historyList.innerHTML = cookieHistory.slice().reverse().map((record, index) => {
                const shortCookie = record.cookie.length > 100 ? 
                    record.cookie.substring(0, 100) + '...' : record.cookie;
                
                return `
                    <div class="cookie-history-item">
                        <div class="cookie-timestamp">${record.timestamp}</div>
                        <div class="cookie-status">${record.status}</div>
                        <div class="cookie-value" id="cookieValue${index}">${shortCookie}</div>
                        <div class="cookie-actions">
                            <button class="btn btn-small" onclick="useCookie('${record.cookie.replace(/'/g, "\\'")}')">使用此Cookie</button>
                            <button class="btn btn-small" onclick="toggleFullCookie(${index}, '${record.cookie.replace(/'/g, "\\'")}')">查看完整</button>
                            <button class="btn btn-small" onclick="copyCookie('${record.cookie.replace(/'/g, "\\'")}')">复制</button>
                        </div>
                    </div>
                `;
            }).join('');
        }

        // 使用指定的Cookie
        function useCookie(cookie) {
            document.getElementById('cookie').value = cookie;
            showNotification('Cookie已填入配置框，请点击保存配置');
        }

        // 切换显示完整Cookie
        function toggleFullCookie(index, fullCookie) {
            const element = document.getElementById(`cookieValue${index}`);
            const shortCookie = fullCookie.length > 100 ? 
                fullCookie.substring(0, 100) + '...' : fullCookie;
            
            if (element.textContent === shortCookie) {
                element.textContent = fullCookie;
            } else {
                element.textContent = shortCookie;
            }
        }

        // 复制Cookie到剪贴板
        async function copyCookie(cookie) {
            try {
                await navigator.clipboard.writeText(cookie);
                showNotification('Cookie已复制到剪贴板');
            } catch (error) {
                // 降级方案
                const textArea = document.createElement('textarea');
                textArea.value = cookie;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                showNotification('Cookie已复制到剪贴板');
            }
        }

        // 加载语音提醒配置
        async function loadSoundConfig() {
            try {
                const response = await fetch('/api/sound-config');
                const result = await response.json();
                
                if (result.success) {
                    document.getElementById('enableSoundNotification').checked = result.enable_sound_notification;
                    document.getElementById('soundFilePath').value = result.sound_file_path || '';
                }
            } catch (error) {
                console.error('加载语音配置失败:', error);
            }
        }

        // 保存语音提醒配置
        async function saveSoundConfig() {
            const enableSound = document.getElementById('enableSoundNotification').checked;
            const soundFilePath = document.getElementById('soundFilePath').value.trim();
            
            try {
                const response = await fetch('/api/sound-config', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        enable_sound_notification: enableSound,
                        sound_file_path: soundFilePath
                    })
                });
                
                const result = await response.json();
                if (result.success) {
                    showNotification('语音设置保存成功');
                } else {
                    showNotification('语音设置保存失败: ' + (result.error || '未知错误'), true);
                }
            } catch (error) {
                showNotification('语音设置保存失败: ' + error.message, true);
            }
        }

        // 测试语音提醒
        async function testSound(videoCount = 1) {
            try {
                const response = await fetch('/api/test-sound', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        video_count: videoCount
                    })
                });
                
                const result = await response.json();
                if (result.success) {
                    showNotification(`测试提示音播放成功 (${videoCount}个新视频)`);
                } else {
                    showNotification('测试提示音失败: ' + (result.error || '未知错误'), true);
                }
            } catch (error) {
                showNotification('测试提示音失败: ' + error.message, true);
            }
        }

        // 视频列表相关变量
        let currentVideoPage = 1;
        const videoPageSize = 10;

        // 加载视频列表
        async function loadVideoList(page = 1) {
            try {
                const authorFilter = document.getElementById('authorFilter').value;
                const statusFilter = document.getElementById('statusFilter').value;
                
                const params = new URLSearchParams({
                    page: page,
                    page_size: videoPageSize,
                    author: authorFilter,
                    status: statusFilter
                });
                
                const response = await fetch(`/api/video-list?${params}`);
                const result = await response.json();
                
                if (result.success) {
                    currentVideoPage = page;
                    updateVideoListDisplay(result.data);
                } else {
                    console.error('加载视频列表失败:', result.error);
                }
            } catch (error) {
                console.error('加载视频列表失败:', error);
            }
        }

        // 更新视频列表显示
        function updateVideoListDisplay(data) {
            const videoList = document.getElementById('videoList');
            const videoPagination = document.getElementById('videoPagination');
            
            if (data.videos.length === 0) {
                videoList.innerHTML = '<div style="text-align: center; color: #666; padding: 40px;">暂无视频记录</div>';
                videoPagination.innerHTML = '';
                return;
            }
            
            // 渲染视频列表
            videoList.innerHTML = data.videos.map(video => {
                const statusClass = getStatusClass(video.progress);
                const shortTitle = video.title.length > 50 ? video.title.substring(0, 50) + '...' : video.title;
                
                return `
                    <div class="video-item">
                        <div class="video-info">
                            <div class="video-title">${shortTitle}</div>
                            <div class="video-meta">
                                <span>👤 ${video.author}</span>
                                <span>📅 ${video.publish_time}</span>
                                <span>🕒 ${video.capture_time}</span>
                                <span>🆔 ${video.video_id}</span>
                            </div>
                            <div style="margin-top: 5px;">
                                <span class="video-status ${statusClass}">${video.progress}</span>
                                ${video.video_url ? `<a href="${video.video_url}" target="_blank" class="video-link" style="margin-left: 10px;">🔗 查看原视频</a>` : ''}
                            </div>
                        </div>
                        <div class="video-actions">
                            <button class="btn btn-small" onclick="updateVideoStatus('${video.video_id}', '待下载')">重置</button>
                            ${video.progress === '下载失败' ? '<button class="btn btn-small btn-danger" onclick="retryDownload(\'' + video.video_id + '\')" title="重新下载">🔄</button>' : ''}
                        </div>
                    </div>
                `;
            }).join('');
            
            // 渲染分页
            renderVideoPagination(data.total_pages, data.current_page);
        }

        // 获取状态样式类
        function getStatusClass(status) {
            switch (status) {
                case '待下载': return 'status-waiting';
                case '下载中': return 'status-downloading';
                case '已下载': return 'status-completed';
                case '下载失败': return 'status-failed';
                default: return 'status-waiting';
            }
        }

        // 渲染分页控件
        function renderVideoPagination(totalPages, currentPage) {
            const pagination = document.getElementById('videoPagination');
            
            if (totalPages <= 1) {
                pagination.innerHTML = '';
                return;
            }
            
            let paginationHTML = '<div class="pagination">';
            
            // 上一页按钮
            paginationHTML += `<button ${currentPage <= 1 ? 'disabled' : ''} onclick="loadVideoList(${currentPage - 1})">上一页</button>`;
            
            // 页码按钮
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);
            
            if (startPage > 1) {
                paginationHTML += '<button onclick="loadVideoList(1)">1</button>';
                if (startPage > 2) {
                    paginationHTML += '<span>...</span>';
                }
            }
            
            for (let i = startPage; i <= endPage; i++) {
                const isCurrentPage = i === currentPage;
                paginationHTML += `<button class="${isCurrentPage ? 'current-page' : ''}" onclick="loadVideoList(${i})">${i}</button>`;
            }
            
            if (endPage < totalPages) {
                if (endPage < totalPages - 1) {
                    paginationHTML += '<span>...</span>';
                }
                paginationHTML += `<button onclick="loadVideoList(${totalPages})">${totalPages}</button>`;
            }
            
            // 下一页按钮
            paginationHTML += `<button ${currentPage >= totalPages ? 'disabled' : ''} onclick="loadVideoList(${currentPage + 1})">下一页</button>`;
            
            paginationHTML += '</div>';
            pagination.innerHTML = paginationHTML;
        }

        // 更新视频状态
        async function updateVideoStatus(videoId, status) {
            try {
                const response = await fetch(`/api/video/${videoId}/status`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        status: status
                    })
                });
                
                const result = await response.json();
                if (result.success) {
                    showNotification('视频状态更新成功');
                    loadVideoList(currentVideoPage);
                } else {
                    showNotification('视频状态更新失败: ' + (result.error || '未知错误'), true);
                }
            } catch (error) {
                showNotification('视频状态更新失败: ' + error.message, true);
            }
        }

        // 清空视频列表
        async function clearVideoList() {
            if (!confirm('确定要清空所有视频记录吗？此操作不可恢复。')) {
                return;
            }
            
            try {
                const response = await fetch('/api/video-list', {
                    method: 'DELETE'
                });
                
                const result = await response.json();
                if (result.success) {
                    showNotification('视频列表已清空');
                    loadVideoList(1);
                } else {
                    showNotification('清空视频列表失败: ' + (result.error || '未知错误'), true);
                }
            } catch (error) {
                showNotification('清空视频列表失败: ' + error.message, true);
            }
        }

        // 重新下载视频
        async function retryDownload(videoId) {
            await updateVideoStatus(videoId, '待下载');
        }

        // 回车键添加主页
        document.getElementById('homepageUrl').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                addHomepage();
            }
        });

        // 回车键筛选视频
        document.getElementById('authorFilter').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                loadVideoList(1);
            }
        });
    </script>
</body>
</html>